<?php
/**
 * JoiGallery - image gallery component for Joostina
 *
 * Frontend AJAX event handler
 *
 * @version 1.0 alpha 12
 * @package JoiGallery
 * @filename joigallery.ajax.php
 * @author JoostinaTeam
 * @copyright (C) 2008-2009 Joostina Team
 * @license see license.txt
 *
 **/

defined('_VALID_MOS') or die();
require_once ($mainframe->getPath('class'));

$task = mosGetParam($_GET,'task','');
$act = mosGetParam($_GET,'act','');
$id = intval(mosGetParam($_GET,'id','0'));

switch($task) {
  
	case 'rate_this':
		return rate_this();
		break;
	case 'get_rate':
		return get_rate();
		break;

	default:
		echo 'error-task';
		return;
}

function rate_this() {
	global $my;
	$database = &database::getInstance();

	$id	= intval(mosGetParam($_REQUEST,'id','0'));
	$add_rate = intval(mosGetParam($_REQUEST, 'rating', 0));

	if(!$my->id) {
		echo '<span class="rate_error">Необходимо авторизоваться</span>';
		return;
	}

	$photo = new joiGalleryPhoto($database);
	$photo->load($id);

	if($my->id == $photo->user_id) {
		echo '<span class="rate_error">Нельзя голосовать за свои фото</span>';
		return;
	}

	$rating  = new joiRating($database, 'com_joigallery');
	$rating->obj_id = $id;

	//Проверяем историю голосований
	if($rating->_history->exist($id, $my->id)) {
		echo '<span class="rate_error">С Вашего последнего голосования прошло слишком мало времени. Попробуйте попозже.</span>';
		return;
	}

	$rating->update($id, $add_rate);
	echo 'Учтено';


}

function get_rate() {
	$database = &database::getInstance();
	$id	= intval(mosGetParam($_REQUEST,'id','0'));

	$rating  = new joiRating($database, 'com_joigallery');
	$rating->obj_id = $id;

	$settings_maxvalue = $rating->_config->max_val;

	$_rating = $rating->get($id);
	$cur_rating = $_rating->total_rating / $_rating->total_hits;


	$curvalueWidth = round(100 / $settings_maxvalue * $cur_rating);
	?>
	<ul class="star-rating" style="width:100px">
		<li class="current-rating" style="width:<?php echo $curvalueWidth;?>%;"><?php echo $cur_rating;?> / <?php echo $settings_maxvalue;?></li>
	</ul>
	<?php
	
}